package com.yimi.appstore.activity;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Browser;
import android.provider.Browser.BookmarkColumns;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Transformation;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.yimi.appstore.R;
import com.yimi.appstore.adapter.GalleryAdapter;
import com.yimi.appstore.adapter.GalleryFlow;
import com.yimi.appstore.download2.DownloadManager;
import com.yimi.appstore.util.AsyncPhoneLoader;
import com.yimi.appstore.util.GlobalConsts;
import com.yimi.appstore.util.AsyncPhoneLoader.ImageCallback;
import com.yimi.appstore.util.Util;

/**
 * 应用详情页
 * 
 * @author Tank
 * 
 */
public class AppDetailActivity extends Activity {

	private static final String TAG = "AppDetailActivity";
	private int width, height;
	private Context mContext;
	private ImageView appCover;
	private TextView appName, appInfoSize, appDownloadCount;
	private Gallery mGallery, mRecommentGallery;
	private TextView appDesc;
	private Button showMoreBtn, downloadBtn, leftArrowBtn, rightArrowBtn;

	public static void lanuchActivity(Context cx, String params) {
		Intent intent = new Intent(cx, AppDetailActivity.class);
		cx.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.app_detail_layout);
		// initUi();
		// getData();
		// initListener();
		// testAddBrowserBooks();
		launchWebView();
	}

	private void initUi() {
		mContext = this;
		width = Util.getScreenWidth(this) / 2;
		height = Util.getScreenHeight(this) / 3 + 100;
		appCover = (ImageView) findViewById(R.id.app_detail_icon);
		appName = (TextView) findViewById(R.id.app_name);
		appInfoSize = (TextView) findViewById(R.id.app_info_version_size);
		appDownloadCount = (TextView) findViewById(R.id.app_download_count);
		mGallery = (Gallery) findViewById(R.id.app_gallery);
		mRecommentGallery = (Gallery) findViewById(R.id.recomment_gallery);
		appDesc = (TextView) findViewById(R.id.app_desc);
		showMoreBtn = (Button) findViewById(R.id.app_desc_show_more);
	}

	private void getData() {
		ArrayList<String> imgUrls = new ArrayList<String>();
		imgUrls.add("http://cdn.image.market.hiapk.com/data/upload/2012/11_29/14/sy_201211291451294133.JPG");
		imgUrls.add("http://cdn.image.market.hiapk.com/data/upload/2012/11_29/14/sy_201211291451515488.JPG");
		imgUrls.add("http://cdn.image.market.hiapk.com/data/upload/2012/11_29/14/sy_201211291452035779.JPG");
		imgUrls.add("http://cdn.image.market.hiapk.com/data/upload/2012/11_29/14/sy_201211291452256271.JPG");
		imgUrls.add("http://cdn.image.market.hiapk.com/data/upload/2012/11_29/14/sy_201211291452461812.JPG");
		GalleryAdapter galleryAdapter = new GalleryAdapter(mContext, imgUrls, width, height);
		mGallery.setAdapter(galleryAdapter);

		ArrayList<String> imgUrls2 = new ArrayList<String>();
		imgUrls2.add("http://static.yingyonghui.com/icon/72/541259.png");
		imgUrls2.add("http://static.yingyonghui.com/icon/72/543500.png");
		imgUrls2.add("http://static.yingyonghui.com/icon/72/542945.png");
		imgUrls2.add("http://static.yingyonghui.com/icon/72/541191.png");
		imgUrls2.add("http://static.yingyonghui.com/icon/72/430478.png");
		GalleryAdapter2 adapter2 = new GalleryAdapter2(mContext, imgUrls2, width, height);
		mRecommentGallery.setAdapter(adapter2);
		mRecommentGallery.setSelection(0);
	}

	private void initListener() {

	}

	private void testLanucher() {
		int i = 0;
		ContentResolver resolver = getContentResolver();
		Uri uri = Uri.parse("content://" + "com.android.launcher.settings" + "/favorites?notify=true");
		Cursor cursor = resolver.query(uri, null, null, null, null);
		while (cursor.moveToNext()) {
			i++;
			Log.d("testLanucher", "" + i);
		}
		ContentValues cv = new ContentValues();
		cv.put("title", "yimi");
		cv.put("intent",
				"#Intent;action=android.intent.action.MAIN;category=android.intent.category.LAUNCHER;launchFlags=0x10200000;component=com.yimi.appstore/.activity.MainActivity;end");
		cv.put("screen", 2);
		cv.put("cellX", 3);
		cv.put("cellY", 3);
		cv.put("iconType", 0);
		cv.put("appWidgetId", -1);
		cv.put("container", -100);
		cv.put("spanX", 1);
		cv.put("spanX", 1);
		cv.put("itemType", 1);
		Uri uri1 = resolver.insert(uri, cv);
	}

	public static final String PREFERENCE_PACKAGE = "com.android.browser";
	public static final String PREFERENCE_NAME = "WebViewSettings";
	public static int MODE = Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE + Context.MODE_APPEND;

	private void addHomepage() {
		Context context = null;
		try {
			context = createPackageContext(PREFERENCE_PACKAGE, Context.CONTEXT_IGNORE_SECURITY);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, MODE);
		try {
			FileOutputStream fos = context.openFileOutput(PREFERENCE_NAME, MODE);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String homepage = settings.getString("homepage", "");
		Editor editor = settings.edit();
		editor.putString("homepage", "http://www.baidu.com");
		boolean result = editor.commit();
	}

	private void testAddBrowserBooks() {
		ContentResolver contentResolver = getContentResolver();
		ContentValues values = new ContentValues();
		values.put(BookmarkColumns.TITLE, "test");
		values.put(BookmarkColumns.URL,
				"http://android.bigresource.com/Android-Setting-Different-Browser-Homepage-through-Code-Possible--L05Uwyibm.html");
		values.put(BookmarkColumns.BOOKMARK, 1);
		Uri uri = contentResolver.insert(Browser.BOOKMARKS_URI, values);

		Intent intent = new Intent();
		intent.setAction("android.intent.action.VIEW");
		Uri content_url = Uri.parse("http://www.cnblogs.com");
		intent.setData(content_url);
		intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
		startActivity(intent);

	}

	WebView webView;

	public void launchWebView() {
		setContentView(R.layout.activity_webview_layout);
		webView = (WebView) findViewById(R.id.webview);
		webView.requestFocus();
		WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);

		webView.setWebViewClient(new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

		});

		webView.addJavascriptInterface(this, "yimi");

		webView.loadUrl("file:///android_asset/index/index.html");
	}

	public void download(String appName, String url) {
		Log.d(TAG, "invoke download() >> url:" + url + ",appName:" + appName);
		DownloadManager downloadManager = DownloadManager.getInstance(mContext);
		downloadManager.addDownloadTask(url, appName, "" , GlobalConsts.MEDIA_MUSIC);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (KeyEvent.KEYCODE_BACK == keyCode && webView.canGoBack()) {
			webView.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public class GalleryAdapter2 extends BaseAdapter {

		private Context mContext;

		private int mGalleryBackground;

		private ArrayList<String> imgArray;

		private int mWidth;

		private int mHeight;

		private AsyncPhoneLoader phoneLoader;

		class ViewHolder {
			ImageView appIcon;
			TextView appName;
		}

		public GalleryAdapter2(Context context, ArrayList<String> arr, int width, int height) {
			mContext = context;
			imgArray = arr;
			mWidth = width;
			mHeight = height;
			// TypedArray array =
			// mContext.obtainStyledAttributes(R.styleable.Gallery);
			// mGalleryBackground =
			// array.getResourceId(R.styleable.Gallery_android_galleryItemBackground,
			// 0);
			// array.recycle();
			phoneLoader = new AsyncPhoneLoader();
		}

		@Override
		public int getCount() {
			return imgArray.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, final ViewGroup parent) {
			View view = convertView;
			ViewHolder vh = null;
			if (view == null || view.getTag() == null) {
				vh = new ViewHolder();
				view = LayoutInflater.from(mContext).inflate(R.layout.recomment_gallery_layout, null);
				vh.appIcon = (ImageView) view.findViewById(R.id.image_item);
				vh.appName = (TextView) view.findViewById(R.id.app_name_item);
				view.setTag(vh);
			} else {
				vh = (ViewHolder) view.getTag();
			}
			try {
				String url = imgArray.get(position);
				vh.appIcon.setTag(url);
				Drawable drawable = phoneLoader.loadDrawable(url, mContext, false, new ImageCallback() {

					@Override
					public void imageLoaded(Drawable imageDrawable, String imageUrl) {
						ImageView imageViewByTag = (ImageView) parent.findViewWithTag(imageUrl);
						if (imageViewByTag != null) {
							if (imageDrawable != null) {
								imageViewByTag.setImageDrawable(imageDrawable);
							} else {
								imageViewByTag.setImageResource(R.drawable.photo_empty);
							}
						}
					}
				});
				if (drawable == null) {
					vh.appIcon.setImageResource(R.drawable.photo_load);
				} else {
					vh.appIcon.setImageDrawable(drawable);
				}
			} catch (Exception e) {
				e.printStackTrace();
				vh.appIcon.setImageResource(R.drawable.icon_empty);
			}

			// vh.appIcon.setScaleType(ScaleType.FIT_XY);
			// vh.appIcon.setBackgroundResource(mGalleryBackground);
			vh.appName.setText("完美世界");
			return view;

		}
	}

}
